﻿using Newtonsoft.Json.Linq;
using NPOI.POIFS.Crypt;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SimpleDesktop
{
    public class Utils
    {
        /**
         * sk-UxGBSRRqNTVcaBJNc7nwzTYK7Khh77gZcgIyEpwjxNzr5x3k
         * sk-proj-wyovAHH5sAX1iyYWqW27T3BlbkFJhu06QPKsTiwUZg6tdmpE
         * sk-nB9hivgokz3wI712OLWKT7LQSbosRRRNuNagRYsN1Shn8iCy
         * 3e8e4cf0-4636-471d-a94f-24dab7c54745
         */
        private const string apiKey = "sk-UxGBSRRqNTVcaBJNc7nwzTYK7Khh77gZcgIyEpwjxNzr5x3k"; // OpenAI API密钥

        public static string GetPrompt(int amount, string Names)
        {
            return "我现在有" + amount + "个桌面快捷方式的路径，我需要你帮我根据文件名称将这些快捷方式路径分类成不同的类别（类别数量尽量不超过" + ((amount + 4) / 5) + "个），使得相同类别的快捷方式有着相同的功能或者作用，例如办公软件、游戏等，要求所有的快捷方式都必须包含。请你将分好的类别用以下的格式进行输出，并保存在一个代码块（用``` ```包围起来）中，除此之外不要输出任何多于字符：\r\n\r\n类别名称1:\r\n- 快捷方式路径1\r\n- 快捷方式路径2\r\n- ...\r\n\r\n类别名称2:\r\n- 快捷方式路径1\r\n- 快捷方式路径2\r\n- ...\r\n\r\n以下是所有的快捷方式路径：\r\n" + Names;
        }

        /**
         * 发送Http请求
         * 请求GPT回答问题
         */
        public static async Task<string> GetChatGptResponse(string prompt)
        {
            var client = new RestClient("https://api.chatanywhere.tech/v1/chat/completions");
            //var client = new RestClient("https://gpt.soruxgpt.com/api/api/v1/chat/completions");
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {apiKey}");

            var body = new
            {
                model = "gpt-3.5-turbo",
                //model = "gpt-4",
                messages = new[]
                {
                    new { role = "system", content = "You are a helpful assistant." },
                    new { role = "user", content = prompt }
                },
                temperature = 0.0
            };

            request.AddJsonBody(body);

            var response = await client.ExecuteAsync(request);
            if (response.IsSuccessful)
            {
                var jsonResponse = JObject.Parse(response.Content);
                return jsonResponse["choices"][0]["message"]["content"].ToString();
            }
            else
            {
                MessageBox.Show("Error: " + response.ErrorMessage + "\nStatusCode: " + response.StatusCode + "\nContent: " + response.Content);
                return null;
            }
        }

        public static PageModels ParsePageModels(string response)
        {
            PageModels models = new PageModels();
            string[] lines = response.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            PageModel model = null;
            bool isIn = false;
            foreach (string line2 in lines)
            {
                string line = line2.Trim();
                if (line.StartsWith("```"))
                {
                    if (isIn) break;
                    else isIn = true;
                    continue;
                }

                if (!isIn) continue;
                if (line.Equals("")) continue;
                else if (line.StartsWith("- "))  // 快捷方式
                {
                    if (model != null)
                    {
                        model.Items.Add(line[2..]);
                    }
                }
                else if (line.EndsWith(":"))  // 类别
                {
                    if (model != null)
                    {
                        models.Pages.Add(model);
                    }
                    model = new PageModel(line.TrimEnd(':'));
                }
            }
            if (model != null)
            {
                models.Pages.Add(model);
            }
            return models;
        }
    }
}
